package com.zwd.deep.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.crypto.digest.DigestUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zwd.deep.common.ResultEnum;
import com.zwd.deep.entity.dto.DoctorsLoginDto;
import com.zwd.deep.entity.dto.DoctorsPageDTO;
import com.zwd.deep.entity.po.Doctors;
import com.zwd.deep.entity.vo.DoctorsVo;
import com.zwd.deep.handle.exception.GlobalException;
import com.zwd.deep.mapper.DoctorsMapper;
import com.zwd.deep.service.IDoctorsService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zwd.deep.utils.JwtUtil;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Objects;

/**
 * <p>
 * 医生信息表 服务实现类
 * </p>
 *
 * @author zwd
 * @since 2025-02-12
 */
@Service
@AllArgsConstructor
public class DoctorsServiceImpl extends ServiceImpl<DoctorsMapper, Doctors> implements IDoctorsService {

    private final DoctorsMapper doctorsMapper;
    @Override
    public String login(DoctorsLoginDto doctorsLoginDto) {
        Doctors doctors = doctorsMapper.selectByJobNumber(doctorsLoginDto.getJobNumber());
        if(Objects.isNull(doctors) || Objects.equals(doctors.getPassword(), DigestUtil.md5Hex(doctorsLoginDto.getPassword()))) {
            throw new GlobalException(ResultEnum.USER_OR_PASSWORD_ERROR);
        }
        HashMap<Object, Object> claims = new HashMap<>();
        claims.put("id", doctors.getDoctorId());
        String token = JwtUtil.generateToken(claims);
        return token;
    }

    @Override
    public DoctorsVo getByDoctorId(Long doctorId) {
        Doctors doctors = doctorsMapper.selectById(doctorId);
        if (Objects.isNull(doctors)) {
            throw new GlobalException(ResultEnum.USER_NOT_EXIST);
        }
        DoctorsVo doctorsVo = new DoctorsVo();
        BeanUtil.copyProperties(doctors, doctorsVo);
        return doctorsVo;
    }

    @Override
    public List<DoctorsVo> getPage(DoctorsPageDTO doctorsPageDTO) {
        Page<Doctors> page = new Page<>(doctorsPageDTO.getPage(), doctorsPageDTO.getSize());
        Page<Doctors> doctorsPage = doctorsMapper.selectPage(page, null);
        List<DoctorsVo> doctorsVos = BeanUtil.copyToList(doctorsPage.getRecords(), DoctorsVo.class);
        return doctorsVos;
    }
}
